﻿using System.Windows;
using System.IO;
using SlideShowGenerator.Data;
using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Media.Animation;
using System;
using System.Windows.Threading;

namespace SlideShowGenerator
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        SSGenerator gen;
        Storyboard anBusy;
        BackgroundWorker investigator;
        BackgroundWorker generator;

        /// <summary>
        /// 
        /// </summary>
        public Window1()
        {
            InitializeComponent();
            anBusy = (Storyboard)this.Resources["anBusy"];
            lstMessages.VerticalContentAlignment = VerticalAlignment.Bottom;

            if( Config.Load() )
            {
                AddMessage("Loaded Configuration File...");
            }
            else
            {
                AddMessage("No Configuration File, Setting Defaults.");
                Config.SetDefaults();
            }
            txtInputDir.Text = Config.InputDir.FullName;
            AddMessage("Input Dir = " + Config.InputDir);
            txtOutputDir.Text = Config.OutputDir.FullName;
            AddMessage("Output Dir = " + Config.OutputDir);
            AddMessage("Max Thumbnail Size = " + Config.MaxThumbnailSize);

            // If we have valid input and output paths, enable the generate images and generate data buttons
            btnGenData.IsEnabled = true;
            btnGenOutImages.IsEnabled = true;

            //If the input directory is valid, try to read in the files.
            if (Config.InputDir.Exists)
            {
                ReadImageFiles(Config.InputDir);
            }
        }

        private void btnGenOutImages_Click(object sender, RoutedEventArgs e)
        {
            if (gen != null)
            {
                if (!Config.OutputDir.Exists)
                {
                    System.Windows.MessageBox.Show("The Output Directory is not valid, please select a valid directory");                    
                    return;
                }

                generator = new BackgroundWorker();
                generator.DoWork += delegate(object osender, DoWorkEventArgs args)
                {
                    gen.GenerateOutputImages(Config.OutputDir); 
                };
                generator.RunWorkerCompleted += delegate(object osender, RunWorkerCompletedEventArgs args)
                {
                    AddMessage("Done generating output images...");
                    anBusy.Stop(this);
                };
                generator.RunWorkerAsync();
                anBusy.RepeatBehavior = RepeatBehavior.Forever;
                anBusy.Begin(this, true);
            }
        }

        private void btnGenData_Click(object sender, RoutedEventArgs e)
        {
            if (gen != null)
            {
                lstMessages.Items.Clear();
                gen.Generate(Config.OutputDir);
            }
        }

        private void btnSelectImageDir_Click(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.SelectedPath = Config.InputDir.FullName;
            DialogResult result = fbd.ShowDialog();
            if (Directory.Exists(fbd.SelectedPath))
            {
                Config.InputDir = new DirectoryInfo(fbd.SelectedPath);

                ReadImageFiles(Config.InputDir);

                // Enable select output dir button
                btnSelectOutDir.IsEnabled = true;
                txtInputDir.Text = Config.InputDir.FullName;
            }
        }

        private void ReadImageFiles(DirectoryInfo InputDir)
        {
            gen = new SSGenerator(InputDir);
            gen.Message += new SSGenerator.SSGeneratorMessageHandler(gen_Message);
            investigator = new BackgroundWorker();
            investigator.DoWork += delegate(object osender, DoWorkEventArgs args)
            {
                gen.Investigate();
            };
            investigator.RunWorkerCompleted += delegate(object osender, RunWorkerCompletedEventArgs args)
            {
                AddMessage("Updating the UI, please wait...");
                lstAlbums.ItemsSource = gen.Albums;
                AddMessage("Done");
                anBusy.Stop(this);
            };
            investigator.RunWorkerAsync();
            anBusy.RepeatBehavior = RepeatBehavior.Forever;
            anBusy.Begin(this, true);
        }

        private void AddMessage(string message)
        {
            lstMessages.Items.Add(message);
            lstMessages.ScrollIntoView(lstMessages.Items[lstMessages.Items.Count - 1]);
        }

        private void gen_Message(object sender, SSGenerator.SSGenMessageEventArgs e)
        {
            if (CheckAccess())
            {
                AddMessage(e.Message);
            }
            else
            {
                Dispatcher.Invoke(DispatcherPriority.Normal, new SSGenerator.SSGeneratorMessageHandler(gen_Message), sender, e);
            }
        }

        private void btnSelectOutDir_Click(object sender, RoutedEventArgs e)
        {
            //yeah, thats the WinForms FolderBrowserDialog, WPF doesn't have one?
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.ShowNewFolderButton = true;
            fbd.SelectedPath = Config.OutputDir.FullName;
            DialogResult result = fbd.ShowDialog();
            if (Directory.Exists(fbd.SelectedPath))
            {
                Config.OutputDir = new DirectoryInfo(fbd.SelectedPath);
                AddMessage("Set output directory: " + Config.OutputDir);

                // Enable generate images and data buttons
                btnGenData.IsEnabled = true;
                btnGenOutImages.IsEnabled = true;
                txtOutputDir.Text = Config.OutputDir.FullName;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Windows.Controls.Button btn = (System.Windows.Controls.Button)sender;
                AlbumData album = (AlbumData)btn.Tag;
                string thumbPath = (string)btn.ToolTip;
                FileInfo f = new FileInfo(thumbPath);
                album.ThumbImage = f.Name;
                album.ThumbImagePath = thumbPath;
                anBusy.Begin(this, true);
                AddMessage("Updating the UI, please wait...");
                lstAlbums.ItemsSource = null;
                lstAlbums.ItemsSource = gen.Albums;
                anBusy.Stop(this);
            }
            catch
            {
                System.Windows.MessageBox.Show("Sorry, something's busted.");
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Options optionDlg = new Options ();
            optionDlg.Show();
        }

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            Config.Save();
            App.Current.Shutdown();
        }
    }
}
